package com.demo.task.ext

import android.util.Log
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.InputStreamReader
import java.lang.Runtime.getRuntime

private const val TAG = "ShellExt"

fun String.runCommand() = kotlin.runCatching {
    Log.i(TAG, "runCommand: $this")
    val process = getRuntime().exec("sh")
    DataOutputStream(process.outputStream).use { os ->
        os.writeBytes("$this\n")
        os.writeBytes("exit\n")
        os.flush()
        process.waitFor()
    }
}.onFailure {
    it.printStackTrace()
}

fun String.runCommandAsResult(): String {
    return kotlin.runCatching {
        val process = getRuntime().exec("sh")
        DataOutputStream(process.outputStream).use { os ->
            os.writeBytes("$this\n")
            os.writeBytes("exit\n")
            os.flush()
            process.waitFor()
        }
        BufferedReader(InputStreamReader(process.inputStream)).use {
            it.readText()
        }
    }.onFailure {
        it.printStackTrace()
    }.getOrNull() ?: orEmpty()

}
